package com.lib.image.glide;

import android.content.Context;

import androidx.annotation.Keep;
import androidx.annotation.NonNull;

import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool;
import com.bumptech.glide.load.engine.cache.DiskLruCacheFactory;
import com.bumptech.glide.load.engine.cache.LruResourceCache;
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator;
import com.bumptech.glide.module.AppGlideModule;
import com.bumptech.glide.request.RequestOptions;

import java.io.File;

import timber.log.Timber;

/**
 * @Author: shalei
 * @Date: 2019-10-28 13:12
 * @Desc: Glide的全部配置，有需要可以自定义
 **/
@GlideModule
@Keep
public class GlobalGlideModule extends AppGlideModule {

    private final long maxMemorySize = Runtime.getRuntime().maxMemory();
    private final int memorySize = (int) (Runtime.getRuntime().maxMemory()) / 8;  // 取1/8最大内存作为最大缓存

    @Override
    public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
        super.applyOptions(context, builder);
//        builder.setDecodeFormat(DecodeFormat.PREFER_RGB_565);
        builder.setMemoryCache(new LruResourceCache(memorySize));
        Timber.d("GlobalGlideModule memorySize %s", memorySize);

        MemorySizeCalculator calculator = new MemorySizeCalculator.Builder(context).build();
        int defaultBitmapPoolSize = calculator.getBitmapPoolSize();
        Timber.d("GlobalGlideModule defaultBitmapPoolSize %s", defaultBitmapPoolSize);

        //修改bitmappool的大小为默认的0.7倍
        int customBitmapPoolSize = (int) (0.7 * defaultBitmapPoolSize);
        builder.setBitmapPool(new LruBitmapPool(customBitmapPoolSize));
        long dealLineSize = 200 * 1024 * 1024;
        //app最大使用内存200M以下，图片质量RGB_565
        if(dealLineSize > maxMemorySize) {
            builder.setDefaultRequestOptions(new RequestOptions().format(DecodeFormat.PREFER_RGB_565));
            Timber.d("GlobalGlideModule defaultBitmapPoolSize dealLineSize");
        }
//        File cacheDir = context.getExternalCacheDir();//指定的是数据的缓存地址
//        int diskCacheSize = 1024 * 1024 * 400;//最多可以缓存多少字节的数据 400M
//        //设置磁盘缓存大小
//        builder.setDiskCache(new DiskLruCacheFactory(cacheDir.getPath(), "glide", diskCacheSize));
    }

    /**
     * 4.0之后不需要在AndroidManifest.xml声明
     *
     * @return 返回false就可以了，不然混淆之后会报错。
     */
    @Override
    public boolean isManifestParsingEnabled() {
        return false;
    }
}
